package com.sx.micowell.framework.binding;


import com.sx.micowell.framework.binding.impl.IBindingAction;
import com.sx.micowell.framework.binding.impl.IBindingConsumer;
import com.sx.micowell.framework.binding.impl.IBindingFunction;

/**
 * @author: YY
 * @time: 2021/6/2
 * @describe Binding指令集, 用于ViewModel与xml之间的数据绑定
 */
public class BindingCommand<T> {
    private IBindingAction bindingAction;
    private IBindingConsumer<T> bindingConsumer;
    private IBindingFunction<Boolean> bindingFunction;

    /**
     * 无参指令
     * @param action
     */
    public BindingCommand(IBindingAction action) {
        this.bindingAction = action;
    }

    /**
     * 带参指令
     * @param consumer
     */
    public BindingCommand(IBindingConsumer<T> consumer) {
        this.bindingConsumer = consumer;
    }

    /**
     * 触发指令
     * @param action 触发命令
     * @param function true-执行, false-不执行
     */
    public BindingCommand(IBindingAction action, IBindingFunction<Boolean> function) {
        this.bindingAction = action;
        this.bindingFunction = function;
    }

    /**
     * @param consumer  带泛型参数触发命令
     * @param function  true-执行, false-不执行
     */
    public BindingCommand(IBindingConsumer<T> consumer, IBindingFunction<Boolean> function) {
        this.bindingConsumer = consumer;
        this.bindingFunction = function;
    }

    /**
     * 执行 BindingAction命令
     */
    public void executeAction() {
        if (bindingAction != null && isExecuteFunction()) {
            bindingAction.call();
        }
    }

    /**
     * 执行带泛型参数的命令
     * @param parameter 泛型参数
     */
    public void executeConsumer(T parameter) {
        if (bindingConsumer != null && isExecuteFunction()) {
            bindingConsumer.call(parameter);
        }
    }

    /**
     * 是否需要执行
     * @return true-执行, false-不执行
     */
    private boolean isExecuteFunction() {
        if (bindingFunction == null) {
            return true;
        }
        return bindingFunction.call();
    }
}
